#include "gamescene.h"

GameScene::GameScene(QWidget *parent)
    : QWidget(parent)
{
    updateTimerId = 0;

    GLWidget = new QGLWidget(QGLFormat(QGL::SampleBuffers));

    // We don't want the scenes to start visible
    setVisible(false);

    // Make this widget the size of the parent window
    resize(parent->width(),parent->height());

    // Set up the graphics Scene
    mainScene = new QGraphicsScene(0,0,width(),height(),this);
    mainScene->setBackgroundBrush(QBrush(Qt::black,Qt::SolidPattern));

    // Set up the graphics viewport
    mainView = new GraphicsPanView(mainScene,this);
    mainView->resize(parent->width(),parent->height());
    mainView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    mainView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    mainView->setFrameStyle(QFrame::NoFrame);

    state = stopped;    // The scene starts stopped

    // connect the focus changed signal so we can detect when the user changes windows and pause the game
    QObject::connect(qApp,SIGNAL(focusChanged(QWidget*,QWidget*)),this,SLOT(focusChanged(QWidget*,QWidget*)));

}

void GameScene::startScene()
{
    setVisible(true);                   // Show the scene
    updateTimerId = startTimer(20);     // Store the timer id so we can kill it when the scene ends
    state = playing;
    start();
}

void GameScene::endScene(GameScene::GameScenes nextScene)
{
    setVisible(false);
    killTimer(updateTimerId);   // Kill the update timer
    state = stopped;
    emit end(nextScene);        // Emit the end signal
}

void GameScene::start()
{
}

void GameScene::timerEvent(QTimerEvent *event)
{
    mainScene->advance();   // Call the advance functions for all the graphics items
}

void GameScene::pauseScene()
{
    killTimer(updateTimerId);
    mainView->setPanEnabled(false);
    mainView->setInteractive(false);
    state = paused;
}

void GameScene::resumeScene()
{
    updateTimerId = startTimer(20);
    mainView->setPanEnabled(true);
    mainView->setInteractive(true);
    state = playing;
}

void GameScene::focusChanged(QWidget *old, QWidget *now)
{
    //if ((old != 0) && (now == 0) && (state == playing))
        //pauseScene();
    //if ((old == 0) && (now != 0) && (state == paused))
        //resumeScene();
}
